package cn.itcast.client;

import cn.itcast.message.xt.IoTLoginRequestMessage;
import cn.itcast.protocol.xt.IoTReqMessageCodec;
import cn.itcast.protocol.xt.IoTProtocolFrameDecoder;
import cn.itcast.server.handler.xt.IoTLoginRespHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class XtClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        IoTReqMessageCodec MESSAGE_CODEC = new IoTReqMessageCodec();
        IoTLoginRespHandler IOT_RESP_HANDLER = new IoTLoginRespHandler();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new IoTProtocolFrameDecoder());
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    ch.pipeline().addLast(IOT_RESP_HANDLER);
                }
            });
            Channel channel = bootstrap.connect("localhost", 8080).sync().channel();
            // 原始的手动传递这么多参数太麻烦，参考RpcClientManager使用动态代理封装，便于调用
            ChannelFuture future = channel.writeAndFlush(
                    new IoTLoginRequestMessage("app_key","app_secret",
                            "dev_id",2,"version_name"));
            channel.closeFuture().sync();
        } catch (Exception e) {
            log.error("client error", e);
        } finally {
            group.shutdownGracefully();
        }
    }

}
